<template>
	<!-- 报告页面 -->
	<view style="height: 100%;">
		<Nav title="报告" :leftIconColor="'#FFF'" @onClickRight="clickRight" />

		<!-- 顶部导航栏切换 -->
		<u-sticky>
			<!-- <view class="" style="background-color: #fff;padding: 20rpx 0;">
				<u-tabs class="tabbar" :list="uTabList" @click="tabChange" lineWidth="30" lineColor="#f56c6c" :activeStyle="{
				        color: '#303133',
				        fontWeight: 'bold',
				        transform: 'scale(1.05)'
				    }" :inactiveStyle="{
				        color: '#606266',
				        transform: 'scale(1)'
				    }" itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;"></u-tabs>
			</view> -->

		</u-sticky>


		<!-- 发起报告  暂时先不用 后续需要打开即可-->
		<view v-if="tabbarIndex==0">
			<StartReport ref="StartReport" :parentObj="{ ...this}" />
		</view>
		<view v-if="tabbarIndex==1" class="">
			<uni-list>
				<uni-list-item title="项目名称" showArrow clickable @click="selectXM">
					<template v-slot:footer>
						<view class="taskName">
							{{ProjectName}}
						</view>
					</template>
				</uni-list-item>
			</uni-list>
			<scroll-view scroll-y="true" :style="{height:height+'px'}" @scrolltolower="lower">
				<view class="list">
					<view class="rightItem" v-for="item in data" :key="item._id" @click="handleView(item._id)">
						<view class="title">
							<text class="text">任务名称: {{item.TaskName}}</text>
						</view>
						<view class="title">
							<text class="text">报告名称: {{item.ReportName}}</text>
							<!-- <view @click.stop="()=>{}">
								<checkbox-group @change="changeItem($event,item)">
									<label>
										<checkbox :value="item._id" :checked="checkArr.includes(item._id)" />
									</label>
								</checkbox-group>
							</view> -->
							<!-- <uni-tag v-if="item.ReportType == 0" :inverted="true" text="个人生成报告" type="primary" /> -->
							<!-- <uni-tag v-else :inverted="true" text="项目生成报告" type="success" /> -->
						</view>
						<view class="userInfo">
							<view class="user">
								<view class="userIcon" v-for="im,ix in item.UserIcons" :key="ix">
									<image :src="im.Icon" mode="aspectFit"></image>
								</view>
							</view>
							<view class="time">
								{{item.CreateTime.split(' ')[0]}}
							</view>
						</view>
					</view>
				</view>
				<uni-load-more iconType="circle" :status="this.data.length >= this.total?'noMore':'loading'" />
			</scroll-view>
		</view>



		<!-- <button class="toReport" size="mini" type="primary" v-show="checkArr.length>0"
			@click="handleView(checkArr)">去生成报告</button> -->
		<!-- <button class="toReport" size="mini" type="primary" v-show="checkArr.length>0"
			@click="echarts.onClick">去生成报告</button> -->
		<!-- <view class="content">
			<view @click="echarts.onClick" :prop="option" :change:prop="echarts.updateEcharts" id="echarts"
				class="echarts"></view>
		</view> -->
		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="进度描述" placeholder="请输入进度描述"
				@confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>
		<listitem ref="listitem" :showAdd="false" @itemClick="XMSelect"></listitem>
	</view>
</template>

<script>
	import {
		mapActions
	} from 'vuex'
	import Nav from '@/components/BackTabBar.vue'
	import listitem from '@/components/listitem/listitem.vue'
	// 发起报告页面
	import StartReport from './startReport.vue'
	export default {
		props: {
			pid: {
				require: false
			}
		},
		components: {
			listitem,
			Nav,
			StartReport
		},
		data() {
			return {
				isSetting: "报告",
				_ID: "",
				// 顶部导航栏默认的tab页面
				tabbarIndex: 0,
				// 顶部导航栏切换
				uTabList: [{
						name: '发起报告',
					},
					{
						name: '报告清单',
					}
				],
				data: [],
				pagination: {
					PageIndex: 1,
					PageRows: 10,
					SortField: "CreateTime",
					SortType: "desc",
				},
				total: 0,
				queryParam: {},
				option: {
					title: {
						text: ''
					},
					xAxis: {
						data: ["楼层", "区域", "专业", "评级"]
					},
					yAxis: {},
					series: [{
						type: 'bar',
						data: [5, 20, 40, 10]
					}]
				},
				checkArr: [],
				EchartsImg: '',
				ProjectSchedule: '',
				ProjectName: '',
				height: 800
			}
		},
		onNavigationBarButtonTap(e) {
			console.log(e)
			uni.navigateTo({
				url: '/pages/user/user'
			})
			return true;
		},
		onLoad() {
			uni.getSystemInfo({
				success: (res) => {
					console.log(res);
					// 可使用高度减去系统状态栏高度减去(自定义导航高度+任务选择高度)
					this.height = res.windowHeight - res.statusBarHeight - 90
				}
			})
		},
		onShow() {
			this.$nextTick(function() {
				console.log('显示report里面组件了')
				this.$refs.StartReport.popMenu()

				let entityProjectXmRwIdObj = uni.getStorageSync('entityProjectXmRwIdObj')
				// // 判断公共数据中是否有上传时候选择的项目和任务对象  如果存在 获取该项目和任务下的数据 不存在不需要获取
				console.log('获取是否加载中----------------------', this.status, entityProjectXmRwIdObj.xmId)
				if (!entityProjectXmRwIdObj.xmId) {
					this.$refs.StartReport.List = []
					this.$refs.StartReport.ProjectName = ''
					this.$refs.StartReport.TaskName = ''
					this.$refs.StartReport.status = "noMore"
					return
				}
				console.log('有entityProjectXmRwIdObj缓存可以调用了上面', entityProjectXmRwIdObj)
				this.$refs.StartReport.ProjectId = entityProjectXmRwIdObj.xmId
				this.$refs.StartReport.TaskId = entityProjectXmRwIdObj.rwId
				this.$refs.StartReport.ProjectName = entityProjectXmRwIdObj.xmName //当选择项目，任务后初始化项目名称和任务名称
				this.$refs.StartReport.TaskName = entityProjectXmRwIdObj.rwName //当选择项目，任务后初始化项目名称和任务名称

				console.log('--=--清空之前上面', this.$refs.StartReport)
				this.$refs.StartReport.getDataList()
			})

			// 检查网络设置，，是否存在网络   设置加载提示  避免后续再没有网络条件下，，接口频繁请求  导致  一直存在正在加载的提示框的问题  只有有网络的情况下去加载
			uni.getNetworkType({
				success: (res) => {
					console.log('获取网络状态', res)
					if (res.networkType === "none") {
						console.log("当前无网络");
						this.status = "noMore"
						uni.showToast({
							title: '当前网络信号异常',
							icon: "none"
						});
					} else {
						console.log("有网络");
						this.$forceUpdate()
						this.getUnreadTotal()
						// if (this.loadData) {
						// 	this.loadData = false
						// 	return
						// }
						this.ProjectId = ''
						this.ProjectName = ''
						this.queryParam.ProjectId = ''
						// this.getDataList()
						this.$nextTick(function() {
							// 获取发起报告列表数据
							console.log(12345)
							this.$refs.StartReport.resetParams() //初始化参数

							let entityProjectXmRwIdObj = uni.getStorageSync('entityProjectXmRwIdObj')
							// // 判断公共数据中是否有上传时候选择的项目和任务对象  如果存在 获取该项目和任务下的数据 不存在不需要获取
							console.log('获取是否加载中----------------------', this.status,
								entityProjectXmRwIdObj.xmId)
							if (!entityProjectXmRwIdObj.xmId) {
								this.$refs.StartReport.List = []
								this.$refs.StartReport.ProjectName = ''
								this.$refs.StartReport.TaskName = ''
								this.$refs.StartReport.status = "noMore"
								return
							}
							console.log('有entityProjectXmRwIdObj缓存可以调用了', entityProjectXmRwIdObj)
							this.$refs.StartReport.ProjectId = entityProjectXmRwIdObj.xmId
							this.$refs.StartReport.TaskId = entityProjectXmRwIdObj.rwId
							this.$refs.StartReport.ProjectName = entityProjectXmRwIdObj
								.xmName //当选择项目，任务后初始化项目名称和任务名称
							this.$refs.StartReport.TaskName = entityProjectXmRwIdObj
								.rwName //当选择项目，任务后初始化项目名称和任务名称

							console.log('--=--清空之前', this.$refs.StartReport)
							this.$refs.StartReport.getDataList()
						})
					}
				}
			})

		},
		methods: {
			...mapActions(['getUnreadTotal']),
			clickRight() {
				uni.navigateTo({
					url: '/pages/user/user'
				})
			},
			// 顶部tab切换
			tabChange(e) {
				console.log('切换', e)
				this.tabbarIndex = e.index

				if (e.index == 0) {
					this.$nextTick(function() {
						// 获取发起报告列表数据
						this.$refs.StartReport.getDataList()
					})
				} else {
					// 获取报告列表数据
					this.getDataList()
				}
			},
			// 选择项目
			selectXM() {
				this.$refs.listitem.open()
				this.checkArr = []
			},
			XMSelect(row) {
				console.log(row)
				this.ProjectId = row.ProjectId
				this.ProjectName = row.ProjectName || row.Name
				this.queryParam.ProjectId = this.ProjectId
				this.getDataList()
			},
			// 报告选择
			changeItem(e, obj) {
				if (e.detail.value.length > 0) {
					this.checkArr.push(obj._id)
				} else {
					let idx = this.checkArr.findIndex(item => item == obj._id)
					this.checkArr.splice(idx, 1)
				}
				console.log(this.checkArr);
			},
			// 生成报告
			toReport(e) {
				this.EchartsImg = e
				this.$refs.inputDialog.open()
			},
			dialogInputConfirm(e) {
				this.ProjectSchedule = e
				uni.showLoading({
					title: 'PDF生成中'
				})
				this.$http('Base_ProjectWork/Base_Project/GetReportPDF', {
					"Ids": this.checkArr,
					"ProjectSchedule": this.ProjectSchedule,
					"EchartsImg": this.EchartsImg
				}).then(res => {
					uni.hideLoading()
					if (res.Success) {
						this.checkArr = []
						this.getDataList()
						this.showModal(res.Data)
					} else uni.showToast({
						icon: 'none',
						title: res.Msg
					})
				})
			},
			// 下拉加载
			lower() {
				if (this.data.length >= this.total) return
				this.concatList()
			},
			concatList() {
				uni.showLoading()
				this.pagination.PageIndex++
				this.$http('Base_ProjectWork/Base_Project/GetReportJsonList', {
						...this.pagination,
						Search: this.queryParam,
					})
					.then((res) => {
						uni.hideLoading()
						if (res.Success) {
							this.data = this.data.concat(res.Data)
							this.total = res.Total
						}
					});
			},
			handleView(data) {
				this.loadData = true
				if (typeof data == 'string') uni.navigateTo({
					url: '/pages/report/reportView?data=' + JSON.stringify([data])
				})
				else uni.navigateTo({
					url: '/pages/report/reportView?data=' + JSON.stringify(data)
				})
			},
			getDataList() {
				// uni.showLoading()
				this.pagination.PageIndex = 1
				this.$http('Base_ProjectWork/Base_Project/GetReportJsonList', {
						...this.pagination,
						Search: this.queryParam,
					})
					.then((res) => {
						// uni.hideLoading()
						if (res.Success) {
							this.data = res.Data;
							this.total = res.Total
							if (typeof res.Data._id == 'string') {
								this._ID = JSON.stringify([res.Data._id])
							} else {
								this._ID = JSON.stringify(res.Data._id)
							}
							console.log('获取this.data', this.data, )
							this.$refs.StartReport.resetParams()
							this.$refs.StartReport.getDataList()
							this.$nextTick(function() {})
							if (this.data.length > 0) this.ProjectName = this.data[0].ProjectName
						}
					});
			},
			// 弹窗提示
			showModal(url) {
				console.log(url);
				uni.showModal({
					title: '提示',
					content: 'PDF已生成,请选择下载或分享',
					cancelText: '分享',
					confirmText: '下载',
					success: (val) => {
						if (val.confirm) {
							this.download(url)
						} else {
							this.share(url)
						}
					}
				})
			},
			// 微信分享
			share(url) {
				uni.share({
					provider: "weixin",
					scene: "WXSceneSession",
					type: 0,
					href: url, // 分享跳转的链接
					title: "报告分享", // 分享标题
					summary: this.entity.ProjectName + "报告", // 分享内容文字
					imageUrl: "https://www.yoojet.com/wx.png", //分享封面图片
					success: function(res) {
						// 此处是调起微信分享成功的回调
					},
					fail: function(err) {
						// 此处是调起微信分享失败的回调
						console.log(err);
					}
				});
			},
			// 下载
			download(url) {
				uni.showLoading({
					title: 'PDF下载中'
				})
				uni.downloadFile({
					url,
					header: {
						'Access-Control-Allow-Origin': '*'
					},
					filePath: '/Download',
					success: (res) => {
						console.log(res);
						uni.openDocument({
							filePath: res.tempFilePath,
							success: function(res) {
								console.log('打开文档成功');
							},
							fail: function(res) {
								uni.showToast({
									title: JSON.stringify(res)
								})
							}
						})
					},
					fail: (err) => {
						uni.showToast({
							icon: 'none',
							title: 'PDF下载失败,请重新尝试'
						})
					},
					complete() {
						uni.hideLoading()
					}
				})
			}
		}
	}
</script>
<script module="echarts" lang="renderjs">
	// 	let myChart
	// 	export default {
	// 		mounted() {
	// 			if (typeof window.echarts === 'function') {
	// 				this.initEcharts()
	// 			} else {
	// 				console.log('123123');
	// 				// 动态引入较大类库避免影响页面展示
	// 				const script = document.createElement('script')
	// 				// view 层的页面运行在 www 根目录，其相对路径相对于 www 计算
	// 				script.src = 'static/echarts.js'
	// 				script.onload = this.initEcharts.bind(this)
	// 				document.head.appendChild(script)
	// 			}
	// 		},
	// 		methods: {
	// 			initEcharts() {
	// 				myChart = echarts.init(document.getElementById('echarts'))
	// 				// 观测更新的数据在 view 层可以直接访问到
	// 				myChart.setOption(this.option)
	// 			},
	// 			updateEcharts(newValue, oldValue, ownerInstance, instance) {
	// 				// 监听 service 层数据变更
	// 				myChart.setOption(newValue)
	// 			},
	// 			async onClick(event, ownerInstance) {
	// 				let pageInstance = app.$options.pageInstances[0]
	// 				uni.showLoading({
	// 					title: '加载中'
	// 				})
	// 				pageInstance.$http('Base_ProjectWork/Base_Project/GetEchartsData', this.checkArr).then(res => {
	// 					pageInstance.option.xAxis.data = res.Data.xAxisData
	// 					pageInstance.option.series[0].data = res.Data.seriesData
	// 					uni.hideLoading()
	// 				})
	// 				// 调用 service 层的方法
	// 				setTimeout(function() {
	// 					const loadCanvas = document.getElementById('echarts'); //将canvas转换成beast64 
	// 					const base64Str = loadCanvas.firstChild.firstChild.toDataURL('image/jpg');
	// 					ownerInstance.callMethod('toReport', base64Str)
	// 				}, 500);
	// 			}
	// 		}
	// 	}
	// 
</script>

<style scoped lang="scss">
	// 覆盖uview组件  tab切换的默认样式
	::v-deep .tabbar {
		.uni-scroll-view {
			.uni-scroll-view-content {
				display: flex;
				justify-content: center;

				.u-tabs__wrapper__nav {
					.u-tabs__wrapper__nav__item {
						// margin: 0 30px;
						// padding-left: 20px;
						// padding-right: 20px;
					}
				}
			}

		}
	}

	/deep/.uni-list-item__container {
		align-items: center;
		padding: 5px;
		padding-left: 15px;
		height: 46px;
	}

	.toReport {
		position: fixed;
		right: 10px;
		bottom: 10px;
		/* #ifdef H5 */
		bottom: 50px;
		/* #endif */
	}

	.taskName {
		padding: 0 15rpx;
		font-size: 36rpx;
		color: #336dba;
		font-weight: 600;
		line-height: 2;
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 480rpx;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.color {
		color: #d1100a;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 100%;
		position: fixed;
		z-index: -1;

		.echarts {
			width: 100%;
			height: 300px;
		}
	}

	.list {
		padding: 10rpx 20rpx;
	}

	.rightItem {
		width: 95%;
		// height: 130rpx;
		background-color: #fff;
		box-shadow: 0 1px 3px 2px rgba(0, 0, 0, 0.1);
		// margin: 0 auto;
		// margin-bottom: 30rpx;
		box-sizing: border-box;
		padding: 15rpx;
		border-radius: 20rpx;

		.title {
			font-size: 16px;
			font-weight: bold;
			font-weight: 600;
			display: flex;
			justify-content: space-between;

			.text {
				flex: 1;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}

			.color {
				width: 60rpx;
			}
		}

		.userInfo {
			display: flex;
			justify-content: space-between;
			margin-top: 10rpx;

			.user {
				flex: 1;
				display: flex;

				.userIcon {
					width: 70rpx;
					height: 70rpx;
					border-radius: 50%;
					overflow: hidden;
					margin-right: 10rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}

			.time {
				color: #999;
			}
		}
	}
</style>